import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '@/utils/store'
import { call } from '@/utils/request'
import { showMsg, showLoading, hideLoading, showSuccess, showBookError } from '@/utils/toast'

var my_booked_num
let timer_scroll
let scrollLeft
Page({
  data: {
    dateList: [],
    dateSelectedIndex: 0,
    venueList: ['室内', '室外'],
    venueSelectedIndex: 0,
    roomList: [
      [1, 2, 3],
      [6, 7, 8, 9, 10, 20, 21, 22, 23, 24],
    ],
    bookSelectedList: [],
    total_money: 0,
    venueMapOneDay: null,
    pay_height: 0,
  },
  onLoad(options) {
    timer_scroll = null
    showLoading()
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['config', 'window_info'],
    })
    this.setData({
      venueSelectedIndex: options.venue === 'in' ? 0 : 1,
    })

    call('/getDateList').then(res => {
      res.forEach(item => {
        item.month_day = item.date.slice(5)
      })
      this.setData({
        dateList: res,
      })
      this.getVenueBookStatusOneDay(res[0].date)
    })
  },
  onUnload() {
    // 解绑
    this.storeBindings.destroyStoreBindings()
  },
  setPayBoxHeight() {
    let {
      bookSelectedList,
      window_info: { bottom, ratio },
    } = this.data
    this.setData({
      pay_height: Math.ceil(bookSelectedList.length / 2) * 40 + bottom * ratio + 115,
    })
  },
  onScrolling(e) {
    scrollLeft = e.detail.scrollLeft
    if (!timer_scroll) {
      timer_scroll = setTimeout(() => {
        this.setData({
          scrollLeft: scrollLeft,
        })
        timer_scroll = null

        // console.log(1);
        // console.log(scrollLeft);
        // clearTimeout(timer_scroll_last)
        // timer_scroll_last = setTimeout(()=>{
        //   this.setData({
        //     scrollLeft: scrollLeft,
        //   })
        //   console.log(0);
        //   console.log(scrollLeft);
        // }, 15)
      }, 5)
    }
  },
  selectVenue({ mark: { index } }) {
    this.setData({
      venueSelectedIndex: index,
    })
  },
  selectDate({ mark: { index } }) {
    if (this.data.dateSelectedIndex === index) return
    this.setData({
      dateSelectedIndex: index,
    })

    this.getVenueBookStatusOneDay(this.data.dateList[index].date)
  },
  getVenueBookStatusOneDay(date) {
    showLoading()
    call('/getVenueBookStatusOneDay/' + date).then(res => {
      this.handleVenueData(res)
      hideLoading()
    })
  },
  handleVenueData(res) {
    my_booked_num = res.my_booked_num

    const o = {}
    res.venue_book_status_one_day.forEach(item => {
      if (!o[item.time]) o[item.time] = {}
      o[item.time][item.room] = item
    })
    this.setData({
      venueMapOneDay: o,
      bookSelectedList: [],
      total_money: 0,
    })
    this.setPayBoxHeight()
  },
  selectRoom({ mark: { venue } }) {
    if (!venue) return
    let {
      bookSelectedList,
      config: { MAX_BOOK_NUM_PER_DAY },
      window_info: { bottom, ratio },
    } = this.data
    if (venue.status === 'CAN_BOOK') {
      if (bookSelectedList.length + my_booked_num >= MAX_BOOK_NUM_PER_DAY) {
        return showMsg('每天最多可预订' + MAX_BOOK_NUM_PER_DAY + '小时！')
        // if (my_booked_num > 0) {
        //   const date_str = date.month_day.slice(0, 2) + '月' + date.month_day.slice(3, 5) + '日'
        //   const leave = (MAX_BOOK_NUM_PER_DAY-my_booked_num) * 2
        //   return showMsg('每天最多可预订'+ (MAX_BOOK_NUM_PER_DAY * 2) +'小时！' + date_str+'您已预订'+my_booked_num*2+'小时，最多还可预订'+ leave +'小时！')
        // } else {
        //   return showMsg('每天最多可预订'+ (MAX_BOOK_NUM_PER_DAY * 2) +'小时！')
        // }
      }
      venue.status = 'MY_SELECTED'
      bookSelectedList.push(venue)
    } else if (venue.status === 'MY_SELECTED') {
      venue.status = 'CAN_BOOK'
      bookSelectedList = bookSelectedList.filter(item => item.id !== venue.id)
    } else {
      return
    }

    this.setData({
      [`venueMapOneDay.${venue.time}.${venue.room}.status`]: venue.status,
      bookSelectedList: bookSelectedList,
      total_money: bookSelectedList.reduce((cur, next) => cur + next.price, 0),
    })
    this.setPayBoxHeight()
  },
  async pay() {
    const { bookSelectedList, total_money } = this.data
    if (bookSelectedList.length === 0) {
      return showMsg('请先选择场地~')
    }
    showLoading()
    const { out_trade_no, wx_pay_res } = await call({
      method: 'POST',
      path: '/payBookVenue',
      data: {
        venue_ids: bookSelectedList.map(item => item.id),
        total_money,
      },
    })
    hideLoading()

    wx_pay_res.package = wx_pay_res.packageVal
    wx.requestPayment(wx_pay_res)
      .then(() => {
        wx.showLoading({
          title: '正在预订场地...',
          mask: true,
        })
        this.paySuccess(out_trade_no)
      })
      .catch(res => {
        call('/closeWxPayOrder/' + out_trade_no)
        wx.redirectTo({
          url: '/pages/order_book_list/index',
        })
      })
  },
  paySuccess(out_trade_no) {
    const id = this.data.bookSelectedList[0].id
    const date = this.data.dateList[this.data.dateSelectedIndex].date
    var timer = setInterval(async () => {
      const res = await call('/getVenueBookStatusOneDay/' + date)
      const venue = res.venue_book_status_one_day.find(item => item.id === id)
      if (venue.status === 'MY_BOOKED') {
        const duration = showSuccess('预订成功！')
        clearInterval(timer)
        timer = undefined
        this.handleVenueData(res)
      }
    }, 1000)

    setTimeout(() => {
      if (timer !== undefined) {
        call('/queryWxPayStatus/' + out_trade_no).catch(res => {
          clearInterval(timer)
          showBookError()
        })
      }
    }, 5000)
  },
})
